package actions;

import java.sql.SQLException;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.RowSet;

import model.StudentModel;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import db.DbException;
//import forms.StudentForm;
import model.AdminModel;

public class AdminAction extends Action {

	private static final boolean DEBUG = true;

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws DbException {
		
		String path = mapping.getPath();
		String input = mapping.getInput();
		
		if (DEBUG) {
			System.err.println("AdminAction: " + path);
			System.err.println("AdminAction: " + input);
		}
		
		if(path.equals("/startReviewing"))
		{
			int numReviewers = AdminModel.getAllReviewersCount();
			// get the number of reviewers, if greater than 2 forward successfully
			if(DEBUG)
			{
				System.err.println("Number of Reviewers: " + Integer.toString(numReviewers));
			}
			if(numReviewers >= 2)
			{
				if(AdminModel.getAppReviewCount() == 0)
					AdminModel.mapReviewersToApplications();
				return mapping.findForward("success");
			}
			else //numReviewers < 2
			{
				// Retrieve all reviewers
				RowSet reviewerSet = AdminModel.getAllReviewers();
				
				// Store the RowSet in the request scope
				request.setAttribute("reviewerSet", reviewerSet);
				
				System.err.println("NOT ENOUGH REVIEWERS");
				
				ActionErrors errors = new ActionErrors();
				errors.add("firstMsgTag1", new ActionMessage("errors.required",
				"More reviewers"));
				saveErrors(request, errors);

				
				return mapping.findForward("failure");
			}
		}

		if(path.equals("/reviewProcess"))
		{
			
			if(AdminModel.getAppReviewCount() == 0)
			{
				// Retrieve all reviewers
				RowSet reviewerSet = AdminModel.getAllReviewers();
				
				// Store the RowSet in the request scope
				request.setAttribute("reviewerSet", reviewerSet);
				
				
				return mapping.findForward("start");

			}
			
			else return mapping.findForward("started");
		}
		
		return mapping.findForward("start");
	}
}